//
//  MuiscDownLoadTsk.m
//  LM_DownLoadDemo
//
//  Created by lanou3g on 16/4/27.
//  Copyright © 2016年 liman. All rights reserved.
//

#import "MuiscDownLoadTsk.h"

@interface MuiscDownLoadTsk ()<NSURLSessionDownloadDelegate>

@property (nonatomic, copy) ProgressBlock progressBlock;
@property (nonatomic, copy) CompleteBlock completeBlock;

@property (nonatomic, strong) NSString *mp3Name;

@property (nonatomic, strong) NSURLSessionDownloadTask *dowmloadTask;
@end

@implementation MuiscDownLoadTsk


- (void)downloadUrl:(NSURL *)url progressBlock:(ProgressBlock)proBlock complete:(CompleteBlock)comBlock{
    self.progressBlock = proBlock;
    self.completeBlock = comBlock;
    self.mp3Name        = [url.absoluteString stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    self.mp3Name        = [self.mp3Name stringByReplacingOccurrencesOfString:@":" withString:@"_"];
//    网络请求
//    delegateQueue回调代理方法时是在主线程 ， 下载任务仍在主线程
    NSURLSession *sesson = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDownloadTask *dowmloadTask = [sesson downloadTaskWithURL:url];
    self.dowmloadTask = dowmloadTask;
    [self.dowmloadTask resume];
}

//开始
- (void)resume{
    [self.dowmloadTask resume];
}

//暂停
- (void)suspend{
    [self.dowmloadTask suspend];
}


//下载

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    //下载进度
    float pregress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
//    block回调
    if (self.progressBlock) {
         self.progressBlock(pregress);
    }
   
    
    
}
//下载完成

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    NSLog(@"%@",[location path]);
//    得到cacehs路径
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [cachesPath stringByAppendingPathComponent:self.mp3Name];
//    移动到Caches文件夹
    [[NSFileManager defaultManager]moveItemAtPath:[location path] toPath:filePath error:nil];
        NSLog(@"%@",filePath);
    if (self.completeBlock) {
        self.completeBlock(filePath);
    }
}
//修改block
- (void)setProgressBlock:(ProgressBlock)proBlock{
    if (_progressBlock != proBlock) {
        _progressBlock = proBlock;
    }
}
- (void)setCompleteBlock:(CompleteBlock)comBlock{
    if (_completeBlock != comBlock) {
        _completeBlock = comBlock;
    }
}


@end
